package com.woniu34.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.woniu.common.token.AccToken;
import com.woniu.common.token.TokenServiceUtil;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class MyZuulFilter extends ZuulFilter {

    @Value("#{'${woniu.zuul.filterAuthUrls}'.split(',')}")
    private List<String> authUrlList;

    @Autowired
    private TokenServiceUtil tokenServiceUtil;



    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //用户当前访问的路径,类似于 /api/user/getInfo
        String requestURI = request.getRequestURI();
        if (!CollectionUtils.isEmpty(authUrlList)) {
            //查询是否用户当前访问的url地址需要验证登录
            for (String url : authUrlList) {
                if(requestURI.contains(url)){
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //从请求头中获取jwt token
        String tokenHeader = request.getHeader("Authorization");
        if(tokenHeader==null){
            tokenHeader=request.getParameter("acctoken");
        }
        if(tokenHeader==null){
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if("Admin-Token".equals(cookie.getName())){
                    tokenHeader=cookie.getValue();
                    break;
                }
            }
        }
        AccToken accToken = null;


        if(tokenHeader==null || (accToken=validateToken(tokenHeader))==null){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }else{
            context.addZuulRequestHeader("userid",String.valueOf(accToken.getUserId()));
        }

        return null;
    }

    //验证token
    private AccToken validateToken(String tokenStr){
        try{
            String token = tokenStr.substring(7);
            return tokenServiceUtil.getAccToken(token);
        }catch(Exception e){
            return null;
        }

    }
}
